#pragma once
#include <iostream>
#include <functional>
#include "Socket.hpp"
#include "InetAddr.hpp"
#include "Protocol.hpp"
#include "Factory.hpp"
#include "Connection.hpp"
using namespace socket_ns;
using namespace protocol_ns;

using cal_t = std::function<Response(Request)>;

class Service
{
public:
    Service(cal_t cal)
        : _cal(cal)
    {
    }
    void Excute(Connection* con)
    {
        std::string message;
        while ((message = DeCode(con->inbuffer())) != "")
        {
            LOG(INFO, "序列化message : %s\n", message.c_str());
            // 3.反序列化
            Request q = Factory::CreateRequest();
            q.DeSerialize(message);
            // 4.求出结果
            Response rs = _cal(q);
            // 5. 结果序列化
            std::string out;
            rs.Serialize(out);

            // 6. 添加抱头
            out = EnCode(out);

            con->outbuffer() += out;

            con->_sender(con);
        }
    }
    ~Service()
    {
    }

private:
    cal_t _cal;
};